class StoreStaff < ActiveRecord::Base
  include StatusObject
  include StaffSalary
  include StaffRecord
  belongs_to :store
  belongs_to :store_department
  belongs_to :store_position
  has_many :salaries, class_name: "StoreStaffSalary", dependent: :destroy
  has_many :adjust_logs, class_name: "StoreAdjustSalaryLog", dependent: :destroy
  has_many :attendences, class_name: "StoreStaffAttendence"
  has_many :rewards, class_name: "StoreStaffReward"
  has_many :disciplines, class_name: "StoreStaffDiscipline"
  has_many :overtimes, class_name: "StoreStaffOvertime"
  has_many :events, class_name: "StoreStaffEvent"
  attr_accessor :password, :password_confirmation
  validates_presence_of :password, if: :password_required?
  validates :login_name, uniqueness: { message: "已经存在!" }#, length: { is: 11 }
  validates :password, confirmation: true, unless: ->(store_staff){store_staff.password.blank?}
  validates :phone_number, length: {is: 11}, numericality: { only_integer: true }
  before_create :encrypt_password

  delegate :name, to: :store_department, allow_nil: true, prefix: true
  delegate :name, to: :store_position, allow_nil: true, prefix: true

  scope :available, -> { where(available: true) }
  scope :without_admin, -> { where(admin: false) }

  ONE_YEAR = 1


  def encrypt_with_salt(txt,salt)
    Digest::SHA256.hexdigest("#{txt}#{salt}")
  end

  def password_connection?
    self.encrypted_password == self.encrypt_with_salt(self.password, self.salt)
  end

  def reset_password!(new_password, pass_confirmation)
    if new_password != pass_confirmation
      return Status.new(success: false, message: '请确保密码的一致性!')
    end
    reset_password(new_password, pass_confirmation)
    self.save!
    Status.new(success: true, message: '恭喜您重置密码成功!!')
  end

  def format_employeed_at
    employeed_at.try(:strftime, "%Y-%m-%d") || Time.now.strftime("%Y-%m-%d")
  end

  def status_i18n
    case status
    when 0 then '试用期'
    when 1 then '正式员工'
    end
  end

  def work_year
    self.update!(employeed_at: Time.now) if !self.employeed_at.present?
    @year ||= Time.now.year - employeed_at.year
    if @year >= ONE_YEAR
      "#{@year}年"
    else
      @month ||= Time.now.month - employeed_at.month
      @month > 0 ? "#{@month}个月" : 0
    end
  end

  private
  def encrypt_password
    self.salt = Digest::MD5.hexdigest("--#{Time.now.to_i}--")
    self.encrypted_password = self.encrypt_with_salt(self.password, self.salt)
  end

  def password_required?
     !password.nil? || !persisted? || !password_confirmation.nil?
  end

  def reset_password(new_password, pass_confirmation)
    self.password = new_password
    self.password_confirmation = pass_confirmation
    encrypt_password
  end

end
